package com.gmako.controller;

import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.gmako.entity.Activityinfo;
import com.gmako.entity.Adress;
import com.gmako.entity.Businessimg;
import com.gmako.entity.Businessinfo;
import com.gmako.entity.Packageinfo;
import com.gmako.entity.Packimg;
import com.gmako.entity.Userinfo;
import com.gmako.service.ActivityinfoService;
import com.gmako.service.BusinessinfoService;
import com.gmako.service.PackageinfoService;
import com.gmako.service.UserinfoService;
import com.gmako.utils.DateUtils;

@Controller
@RequestMapping("/packinfo.do")
public class PackageInfoController {
	@Autowired(required=false) 
	private PackageinfoService packageinfoService;
	@Autowired(required = false)
	private BusinessinfoService businessinfoService;
	@Autowired(required=false) 
	private ActivityinfoService activityinfoService;
	@Autowired(required=false) 
	private UserinfoService userinfoService;

	
	@RequestMapping(params = "method=add")
	public String info(HttpServletRequest request){
		Packageinfo p=new Packageinfo();
		p.setAdditionalTips(request.getParameter("AdditionalTips"));
		p.setPackageExplain(request.getParameter("PackageExplain"));
		p.setPackageMaxPeople(Integer.parseInt(request.getParameter("PackageMaxPeople")));
		p.setPackageName(request.getParameter("PackageName"));
		p.setPackageSummary(request.getParameter("PackageSummary"));
		p.setPrice(Integer.parseInt(request.getParameter("price")));
		p.setRealPrice(Integer.parseInt(request.getParameter("realPrice")));
		return "addpackage";
	}
	
	/**
	 * 显示提交套餐信息
	 * @author yezhenchi
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "method=viewAddPackage")
	public ModelAndView viewBusinessDetail(HttpServletRequest request,
			HttpServletResponse response, Businessinfo businessinfo){
//		int businessId = 0;
//		HttpSession session = request.getSession();
//		Userinfo userinfo = (Userinfo)session.getAttribute("loginUser");
//		//根据登录ID查询商家ID
//		Businessinfo bui = userinfoService.businessinfo(userinfo.getId());
//		businessId = bui.getId();
//		System.out.println("用户ID为"+userinfo.getId());
//		System.out.println("商家ID为"+businessId);
////		System.out.println("取到的信息为"+us.getUseremail());
//		request.setAttribute("businessId", businessId);
		return new ModelAndView("addpackage");
	}
	
	
	/**
	 * 提交套餐
	 * 
	 * @author yezhenchi
	 * @param request
	 * @param response
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(params = "method=addPack")
	public String addPackInfo(HttpServletRequest request,
			HttpServletResponse response , Packageinfo packageinfo) throws ParseException {
		int businessId = 0;
		HttpSession session = request.getSession();
		Userinfo userinfo = (Userinfo)session.getAttribute("loginUser");
		//根据登录ID查询商家ID
		Businessinfo bui = userinfoService.businessinfo(userinfo.getId());
		businessId = bui.getId();
//		System.out.println("用户ID为"+userinfo.getId());
//		System.out.println("商家ID为"+businessId);
		packageinfo.setBusinessInfoId(businessId);
		if(packageinfo.getPackType()==2){
			String dateStr1 = request.getParameter("startTime1");
			String dateStr2 = request.getParameter("endTime1");
			String dateStr3=  request.getParameter("termStartTime1");
			String dateStr4=  request.getParameter("termEndTime1");
		
			SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date1 = DateUtils.StringToDate(dateStr1);
			String time1 = df1.format(date1);
			Timestamp ts1 = Timestamp.valueOf(time1);
			System.out.println(ts1);
			
			SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date2 = DateUtils.StringToDate(dateStr2);
			String time2 = df2.format(date2);
			Timestamp ts2 = Timestamp.valueOf(time2);
			
			SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date3 = DateUtils.StringToDate(dateStr3);
			String time3 = df3.format(date3);
			Timestamp ts3 = Timestamp.valueOf(time3);
			
			SimpleDateFormat df4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date4 = DateUtils.StringToDate(dateStr4);
			String time4 = df4.format(date4);
			Timestamp ts4 = Timestamp.valueOf(time4);
			packageinfo.setStartTime(ts1);
			packageinfo.setEndTime(ts2);
			packageinfo.setTermStartTime(ts3);
			packageinfo.setTermEndTime(ts4);
		}
		packageinfoService.addpackageInfo(packageinfo);
		Packimg packimg = new Packimg();
		packimg.setPackageId(packageinfo.getId());
		if(request.getParameterValues("text")!=null){
			String[] imgs = request.getParameterValues("text");
			for (String img : imgs) {
				if (img != null) {
					packimg.setImgName(img);
					packageinfoService.save(packimg);
				}
			}
		}else{
			request.setAttribute("businessId", packageinfo.getBusinessInfoId());
			return "successPostpack";
		}
		request.setAttribute("businessId", packageinfo.getBusinessInfoId());
		return "successPostpack";
//		return null;
	}
	
	/**
	 *  团购详细页跳转
	 * @param request
	 * @param response
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(params = "method=tuangouDetail")
	public String tuangouDetail(HttpServletRequest request,
			HttpServletResponse response) throws ParseException {
		int packageId = 0;
		String rpackageId = request.getParameter("packageId");
		if (rpackageId != null && rpackageId != "") {
			packageId = Integer.parseInt(rpackageId.toString());
		}
//		System.out.println(packageId);
		//根据套餐ID 获取套餐信息
		Packageinfo pakageinfo = packageinfoService.getPackageinfo(packageId);
		//根据套餐ID 获取商家信息
		int businessId = pakageinfo.getBusinessInfoId();
		Businessinfo binfo = businessinfoService.findBusinessInfoByBid(businessId);
		List<Businessimg> bimg = businessinfoService.findBusinessImgs(businessId);
		List<Packimg> packimg = packageinfoService.findPackageImgs(packageId);
		//第一张设为封面
		String cover = packimg.get(0).getImgName();
		request.setAttribute("pakageinfo", pakageinfo);
		request.setAttribute("binfo", binfo);
		request.setAttribute("packimg", packimg);
		request.setAttribute("bimg", bimg);
		request.setAttribute("cover", cover);
		return "tuangouDetail";
	}
	
	/**
	 * 活动详细页跳转
	 * @param request
	 * @param response
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(params = "method=huodongDetail")
	public String huodongDetail(HttpServletRequest request,
			HttpServletResponse response) throws ParseException {
		int activityId = 0;
		String ractivityId = request.getParameter("aid");
		if (ractivityId != null && ractivityId != "") {
			activityId = Integer.parseInt(ractivityId.toString());
		}
		Activityinfo activityinfo = activityinfoService.getActivityinfo(activityId);
		//获取套餐信息
		int packageId = activityinfo.getPackageInfoId();
		Packageinfo pakageinfo = packageinfoService.getPackageinfo(packageId);
		//获取商家信息
		int businessId = activityinfo.getBusinessInfoId();
//		System.out.println(activityinfo.getActivityinfoContext());
		Businessinfo binfo = businessinfoService.findBusinessInfoByBid(businessId);
		List<Businessimg> bimg = businessinfoService.findBusinessImgs(businessId);
		List<Packimg> packimg = packageinfoService.findPackageImgs(packageId);
		//数量
		int num = activityinfo.getManCount()+activityinfo.getWomanCount();
		//第一张设为封面
		String cover = packimg.get(0).getImgName();
		request.setAttribute("pakageinfo", pakageinfo);
		request.setAttribute("binfo", binfo);
		request.setAttribute("packimg", packimg);
		request.setAttribute("bimg", bimg);
		request.setAttribute("cover", cover);
		request.setAttribute("activityinfo", activityinfo);
		request.setAttribute("num", num);
		return "huodongDetail";
	}
	
	
	/**
	 * 获取绝对路径
	 * 
	 * @param request
	 * @param path
	 * @return
	 */
	public String getRealPath(HttpServletRequest request, String path) {
		return request.getSession().getServletContext().getRealPath(path);
	}

	/**
	 * 生成ID
	 * 
	 * @return
	 */
	public static String generateId() {
		return new Date().getTime() + getRandomString(5);
	}

	/**
	 * 生成随机字符串(数字+字母)
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(3);
			long result = 0;
			switch (number) {
			case 0:
				result = Math.round(Math.random() * 25 + 65);
				sb.append(String.valueOf((char) result));
				break;
			case 1:
				result = Math.round(Math.random() * 25 + 97);
				sb.append(String.valueOf((char) result));
				break;
			case 2:
				sb.append(String.valueOf(new Random().nextInt(10)));
				break;
			}
		}
		return sb.toString();
	}
	
	/**
	 * @author Warlock
	 * 
	 * 商户信息 -----商户图片————上传
	 * 
	 * @throws Exception
	 */
	@RequestMapping(params = "method=upload")
	public void upload(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String path = getRealPath(request, "/images/packageImg/");
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdir();
		}
		//
		// // 缩放图片
		// String zoomPath = getRealPath(request, "images/houseImg/zoom");
		// File dirZoom = new File(zoomPath);
		// if (!dirZoom.exists()) {
		// dirZoom.mkdir();
		// }

		MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
		MultipartFile file = multipart.getFile("Filedata");

		if (file == null || file.isEmpty()) {
			// 文件不存在
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}

		String newFileName = generateId();

		// 原始图片名称
		String y_fileName = file.getOriginalFilename();

		// 原始图片后缀
		String extname = file.getOriginalFilename().substring(
				y_fileName.lastIndexOf("."));

		// 生成图片 名称
		String fileName = newFileName + extname;
		String fromFileStr = dir.getAbsolutePath() + File.separator + fileName;
		FileCopyUtils.copy(file.getBytes(), new File(dir.getAbsolutePath()
				+ File.separator + fileName));
		response.getWriter().print(fileName);
		request.setAttribute("newFileName", fileName);
	}
}
